package main

import (
	"context"
	"github.com/go-kit/kit/auth/jwt"
	transport_grpc "github.com/go-kit/kit/transport/grpc"
	"github.com/joho/godotenv"
	"google.golang.org/grpc"
	"gysa-share01/common"
	user_service "gysa-share01/user-service"
	"gysa-share01/user-service/auth"
	"gysa-share01/user-service/user"
	service_user "gysa-share01/user-service/user/proto"
	"net"
)

type userGrpcService struct {
	infoHandler transport_grpc.Handler
}

//实现grpc server接口
func (u userGrpcService) Info(ctx context.Context, request *service_user.InfoRequest) (*service_user.InfoResponse, error) {
	_, rep, err := u.infoHandler.ServeGRPC(ctx, request)
	if err != nil {
		return nil, err
	}
	return rep.(*service_user.InfoResponse), nil
}

func main() {
	log := common.Logger
	//加载.env
	err := godotenv.Load()
	if err != nil {
		log.Println("Error loading .env file")
	}
	var (
		server                  = grpc.NewServer()
		userGrpcServiceInstance = userGrpcService{}
	)

	sc, err := net.Listen("tcp", user_service.GrpcHost+":"+user_service.GrpcPort)
	if err != nil {
		log.Fatalf("unable to listen: %+v", err)
	}
	defer server.GracefulStop()
	var service user.UserServiceInterface
	service = user.UserService{}
	userInfoEndpoint := user.MakeGrpcInfoEndpoint(service)
	userInfoEndpoint = jwt.NewParser(auth.KeyFunc, auth.JWTMethod, auth.AuthClaimsFactory)(userInfoEndpoint)
	userGrpcServiceInstance.infoHandler = transport_grpc.NewServer(
		userInfoEndpoint,
		user.DecodeRequest,
		user.EncodeResponse,
		transport_grpc.ServerBefore(jwt.GRPCToContext()),
	)

	//启动grpc服务
	service_user.RegisterUserServer(server, userGrpcServiceInstance)
	err = server.Serve(sc)
	if err != nil {
		log.Fatal(err)
	}
}
